<template>
  <a-modal
    v-model:visible="visible"
    modal-class="modal-form-large"
    title-align="start"
    title="重置密码"
    :top="120"
    :align-center="false"
    :draggable="true"
    :mask-closable="false"
    :unmount-on-close="true"
    :ok-button-props="{ disabled: loading }"
    :cancel-button-props="{ disabled: loading }"
    :on-before-ok="handlerOk"
    @close="handleClose"
  >
    <a-spin class="form-full" :loading="loading">
      <BhForm ref="formRef" :columns="formColumns" :model-value="formModel" :options="options">
        <template #username>
          <a-input v-model="updateUser.username"    :disabled="true"></a-input>
        </template>
        <template #nickname>
          <a-input v-model="updateUser.nickname"  :disabled="true"></a-input>
        </template>
      </BhForm>
    </a-spin>
  </a-modal>
</template>

<script lang="ts" setup>
  import  { type UserQueryResponse,type  UserUpdateRequest,resetUserPassword } from '@/api/system/user';
  import {useLoading} from '@/hooks/modules/useLoading';
  import useVisible from '@/hooks/visible';
  import { Message } from '@arco-design/web-vue';
  import {BhForm, Columns, Options} from "@/components/BhForm";

  const options: Options = {
    form: { size: 'large' },
    btns: { hide: true },
  }
  const formColumns: Columns = reactive([
    {
      label: '用户名',
      field: 'username',
      type: 'input',
    },
    {
      label: '昵称',
      field: 'nickname',
      type: 'input',
    },
    {
      label: '密码',
      field: 'password',
      type: 'input-password',
      rules: [
          { required: true, message: '请输入新密码' },
         {
           minLength: 6,
          maxLength: 12,
           message: '密码长度需要在 8-32 位之间',
        },
      ],
    },
  ])

  const { visible, setVisible } = useVisible();
  const { loading, setLoading } = useLoading();
  const formRef = ref<InstanceType<typeof BhForm>>()
  const formModel = ref<UserUpdateRequest>({});
  const updateUser = ref<UserQueryResponse>({} as UserQueryResponse);
  // 渲染表单
  const renderForm = (record: any) => {
    updateUser.value = { ...record };
    formModel.value = {
      password: undefined,
    };
  };
  const open = (record: any) => {
    renderForm(record);
    setVisible(true);
  };
  const handlerClear = () => {
    setLoading(false);
  };

  defineExpose({ open });

  const handlerOk = async () => {
    setLoading(true);
    try {
      // 验证参数
      const error = await formRef.value?.formRef?.validate()
      if (error)  return false;
      // 修改
      await resetUserPassword({
        id: updateUser.value.id,
        password: formModel.value.password,
      });
      Message.success('修改成功');
      // 清空
      handlerClear();
      return true;
    } catch (e) {
      return false;
    } finally {
      setLoading(false);
    }
  };
  const handleClose = () => {
    handlerClear();
  };
</script>

<style scoped lang="less"></style>
